package com.geek.advice;

import com.geek.bean.BaseRespVo;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ValidationControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseRespVo baseRespVo(MethodArgumentNotValidException e){
        //拿到校验失败的信息
        FieldError fieldError = e.getFieldError();
        //校验失败的参数key
        String field = fieldError.getField();
        //校验失败的参数value
        Object value = fieldError.getRejectedValue();
        // 校验消息 → 注解中的message
        String message = fieldError.getDefaultMessage();

        return BaseRespVo.badArgument(field, message);
    }
}
